package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
)

// 定义请求和响应的结构体
type ChatRequest struct {
	Model     string    `json:"model"`
	Messages  []Message `json:"messages"`
	MaxTokens int       `json:"max_tokens,omitempty"`
	Stream    bool      `json:"stream,omitempty"`
}

type Message struct {
	Role    string `json:"role"`
	Content string `json:"content"`
}

type ChatResponse struct {
	ID      string `json:"id"`
	Object  string `json:"object"`
	Created int64  `json:"created"`
	Choices []struct {
		Index        int     `json:"index"`
		Message      Message `json:"message"`
		FinishReason string  `json:"finish_reason"`
	} `json:"choices"`
	Usage struct {
		PromptTokens     int `json:"prompt_tokens"`
		CompletionTokens int `json:"completion_tokens"`
		TotalTokens      int `json:"total_tokens"`
	} `json:"usage"`
}

const (
	apiKey string = "api_key"
)

func main() {
	// 创建聊天请求
	request := ChatRequest{
		Model: "deepseek-chat", // 根据DeepSeek实际模型名称调整
		Messages: []Message{
			{
				Role:    "system",
				Content: "You are a helpful assistant",
			},
			{
				Role:    "user",
				Content: "中国四大名著有那些",
			},
		},
		MaxTokens: 2048,
		Stream: false,
	}

	// 将请求转换为JSON
	requestBody, err := json.Marshal(request)
	if err != nil {
		fmt.Printf("JSON编码错误: %v\n", err)
		return
	}

	// 创建HTTP请求
	req, err := http.NewRequest("POST", "https://api.deepseek.com/chat/completions", bytes.NewBuffer(requestBody))
	if err != nil {
		fmt.Printf("创建请求错误: %v\n", err)
		return
	}

	// 设置请求头
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Accept", "application/json")
	req.Header.Set("Authorization", "Bearer "+apiKey)

	// 发送请求
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Printf("请求错误: %v\n", err)
		return
	}
	defer resp.Body.Close()

	// 读取响应
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Printf("读取响应错误: %v\n", err)
		return
	}

	// 检查HTTP状态码
	if resp.StatusCode != http.StatusOK {
		fmt.Printf("API返回错误: %s\n", resp.Status)
		fmt.Printf("响应体: %s\n", body)
		return
	}

	// 解析响应
	var response ChatResponse
	err = json.Unmarshal(body, &response)
	if err != nil {
		fmt.Printf("JSON解析错误: %v\n", err)
		return
	}

	// 输出AI的回答
	if len(response.Choices) > 0 {
		fmt.Println("AI回答:")
		fmt.Println(response.Choices[0].Message.Content)
	} else {
		fmt.Println("未收到有效回答")
	}
}
